<template>
  <div class="register-page">
    <div class="register-container">
      <!-- 左侧品牌区域 -->
      <div class="brand-section">
        <div class="brand-content">
          <div class="brand-logo">
            <el-icon :size="80" color="white">
              <House />
            </el-icon>
          </div>
          <h1 class="brand-title">加入我们</h1>
          <p class="brand-subtitle">开启您的洗护服务之旅</p>
          <div class="brand-features">
            <div class="feature-item">
              <el-icon><UserFilled /></el-icon>
              <span>专属服务</span>
            </div>
            <div class="feature-item">
              <el-icon><Present /></el-icon>
              <span>新人优惠</span>
            </div>
            <div class="feature-item">
              <el-icon><Star /></el-icon>
              <span>优质体验</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧注册表单 -->
      <div class="form-section">
        <div class="form-card">
          <div class="form-header">
            <h2>创建账户</h2>
            <p>请填写以下信息完成注册</p>
          </div>

          <el-form 
            :model="form" 
            :rules="rules" 
            ref="formRef" 
            class="register-form"
            @submit.prevent="handleRegister"
          >
            <el-form-item prop="username" label="用户名">
              <el-input
                v-model="form.username"
                placeholder="请输入用户名，支持中英文"
                size="large"
                clearable
                @blur="checkUsernameAvailable"
              >
                <template #prefix>
                  <el-icon><User /></el-icon>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item prop="mobile" label="手机号">
              <el-input
                v-model="form.mobile"
                placeholder="请输入手机号"
                size="large"
                clearable
                maxlength="11"
                @input="handleMobileInput"
              >
                <template #prefix>
                  <el-icon><Phone /></el-icon>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item prop="email" label="邮箱">
              <el-input
                v-model="form.email"
                placeholder="请输入邮箱地址"
                size="large"
                clearable
              >
                <template #prefix>
                  <el-icon><Message /></el-icon>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item prop="code" label="验证码">
              <div class="code-input">
                <el-input
                  v-model="form.code"
                  placeholder="请输入6位验证码"
                  size="large"
                  clearable
                  maxlength="6"
                  @input="handleCodeInput"
                >
                  <template #prefix>
                    <el-icon><Lock /></el-icon>
                  </template>
                </el-input>
                <el-button 
                  @click="sendCode" 
                  :disabled="countdown > 0 || !form.mobile || !/^1[3-9]\d{9}$/.test(form.mobile)"
                  class="code-btn"
                  size="large"
                  :loading="sendingCode"
                >
                  {{ countdown > 0 ? `${countdown}s` : '获取验证码' }}
                </el-button>
              </div>
            </el-form-item>

            <el-form-item prop="password" label="密码">
              <el-input
                v-model="form.password"
                type="password"
                placeholder="请输入6-20位密码"
                size="large"
                show-password
                clearable
                @input="checkPasswordStrength"
              >
                <template #prefix>
                  <el-icon><Lock /></el-icon>
                </template>
              </el-input>
              <!-- 密码强度指示器 -->
              <div class="password-strength" v-if="form.password">
                <div class="strength-bar">
                  <div 
                    class="strength-fill" 
                    :style="{ width: passwordStrength.width, backgroundColor: passwordStrength.color }"
                  ></div>
                </div>
                <span class="strength-text" :style="{ color: passwordStrength.color }">
                  {{ passwordStrength.text }}
                </span>
              </div>
            </el-form-item>

            <el-form-item prop="confirmPassword" label="确认密码">
              <el-input
                v-model="form.confirmPassword"
                type="password"
                placeholder="请再次输入密码"
                size="large"
                show-password
                clearable
              >
                <template #prefix>
                  <el-icon><Lock /></el-icon>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item prop="agreement">
              <el-checkbox v-model="form.agreement" size="large">
                我已阅读并同意
                <el-link type="primary" @click="showTermsDialog = true">《用户协议》</el-link>
                和
                <el-link type="primary" @click="showPrivacyDialog = true">《隐私政策》</el-link>
              </el-checkbox>
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                size="large"
                :loading="loading"
                @click="handleRegister"
                class="register-btn"
                :disabled="!isFormValid"
              >
                注册
              </el-button>
            </el-form-item>
          </el-form>

          <div class="form-footer">
            <div class="divider">
              <span>或</span>
            </div>
            
            <div class="login-prompt">
              <span>已有账号？</span>
              <router-link to="/login" class="login-link">立即登录</router-link>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 用户协议对话框 -->
    <el-dialog v-model="showTermsDialog" title="用户协议" width="600px">
      <div class="agreement-content">
        <h3>服务条款</h3>
        <p>欢迎使用本洗护服务平台。请仔细阅读以下条款：</p>
        <ol>
          <li>用户注册时提供的信息必须真实、准确、完整</li>
          <li>用户应妥善保管账户信息，对账户活动负责</li>
          <li>用户同意接受平台推送的服务相关信息</li>
          <li>禁止利用平台进行违法违规活动</li>
          <li>平台保留根据实际情况修改服务条款的权利</li>
        </ol>
        <p>继续使用本服务即表示您同意遵守上述条款。</p>
      </div>
      <template #footer>
        <el-button @click="showTermsDialog = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 隐私政策对话框 -->
    <el-dialog v-model="showPrivacyDialog" title="隐私政策" width="600px">
      <div class="agreement-content">
        <h3>隐私保护</h3>
        <p>我们非常重视您的隐私保护：</p>
        <ol>
          <li>我们只收集提供服务所必需的个人信息</li>
          <li>您的个人信息将被严格保密，不会泄露给第三方</li>
          <li>我们使用行业标准的安全措施保护您的数据</li>
          <li>您有权查看、修改或删除个人信息</li>
          <li>我们会及时通知您隐私政策的重要变更</li>
        </ol>
        <p>如有疑问，请联系我们的客服团队。</p>
      </div>
      <template #footer>
        <el-button @click="showPrivacyDialog = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { authApi } from '@/services/api'
import { ElMessage } from 'element-plus'
import { User, Phone, Message, Lock, House, UserFilled, Present, Star } from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const formRef = ref()
const loading = ref(false)
const sendingCode = ref(false)
const countdown = ref(0)
const showTermsDialog = ref(false)
const showPrivacyDialog = ref(false)

const form = reactive({
  username: '',
  mobile: '',
  email: '',
  code: '',
  password: '',
  confirmPassword: '',
  agreement: false
})

// 密码强度检测
const passwordStrength = ref({
  score: 0,
  width: '0%',
  color: '#f56c6c',
  text: '弱'
})

const validateUsername = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入用户名'))
  } else if (value.length < 2 || value.length > 20) {
    callback(new Error('用户名长度为2-20个字符'))
  } else if (!/^[a-zA-Z0-9\u4e00-\u9fa5_]+$/.test(value)) {
    callback(new Error('用户名只能包含中英文、数字和下划线'))
  } else {
    callback()
  }
}

const validateMobile = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入手机号'))
  } else if (!/^1[3-9]\d{9}$/.test(value)) {
    callback(new Error('请输入正确的手机号'))
  } else {
    callback()
  }
}

const validatePassword = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入密码'))
  } else if (value.length < 6 || value.length > 20) {
    callback(new Error('密码长度为6-20位'))
  } else {
    callback()
  }
}

const validateConfirmPassword = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请确认密码'))
  } else if (value !== form.password) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

const validateAgreement = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请阅读并同意用户协议和隐私政策'))
  } else {
    callback()
  }
}

const rules = {
  username: [{ validator: validateUsername, trigger: 'blur' }],
  mobile: [{ validator: validateMobile, trigger: 'blur' }],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码为6位数字', trigger: 'blur' }
  ],
  password: [{ validator: validatePassword, trigger: 'blur' }],
  confirmPassword: [{ validator: validateConfirmPassword, trigger: 'blur' }],
  agreement: [{ validator: validateAgreement, trigger: 'change' }]
}

// 计算表单是否有效
const isFormValid = computed(() => {
  return form.username && 
         form.mobile && 
         form.code && 
         form.password && 
         form.confirmPassword && 
         form.agreement &&
         form.password === form.confirmPassword &&
         /^1[3-9]\d{9}$/.test(form.mobile) &&
         form.code.length === 6
})

// 处理手机号输入
const handleMobileInput = (value) => {
  // 只允许数字
  form.mobile = value.replace(/\D/g, '')
}

// 处理验证码输入
const handleCodeInput = (value) => {
  // 只允许数字
  form.code = value.replace(/\D/g, '')
}

// 检查用户名可用性
const checkUsernameAvailable = async () => {
  if (!form.username || form.username.length < 2) return
  
  try {
    await authApi.checkUsernameAvailable(form.username)
  } catch (error) {
    if (error.response?.status === 409) {
      ElMessage.warning('用户名已被使用，请换一个')
    }
  }
}

// 检查密码强度
const checkPasswordStrength = () => {
  const password = form.password
  if (!password) {
    passwordStrength.value = { score: 0, width: '0%', color: '#f56c6c', text: '弱' }
    return
  }

  let score = 0
  
  // 长度加分
  if (password.length >= 8) score += 25
  if (password.length >= 12) score += 15
  
  // 包含数字
  if (/\d/.test(password)) score += 20
  
  // 包含小写字母
  if (/[a-z]/.test(password)) score += 20
  
  // 包含大写字母
  if (/[A-Z]/.test(password)) score += 20
  
  // 包含特殊字符
  if (/[^a-zA-Z0-9]/.test(password)) score += 20

  let width, color, text
  if (score <= 30) {
    width = '25%'
    color = '#f56c6c'
    text = '弱'
  } else if (score <= 50) {
    width = '50%'
    color = '#e6a23c'
    text = '中等'
  } else if (score <= 80) {
    width = '75%'
    color = '#409eff'
    text = '良好'
  } else {
    width = '100%'
    color = '#67c23a'
    text = '强'
  }

  passwordStrength.value = { score, width, color, text }
}

// 发送验证码
const sendCode = async () => {
  if (!form.mobile || !/^1[3-9]\d{9}$/.test(form.mobile)) {
    ElMessage.warning('请先输入正确的手机号')
    return
  }
  
  try {
    sendingCode.value = true
    await authApi.sendSmsCode(form.mobile, 'register')
    ElMessage.success('验证码已发送，请注意查收')
    
    // 开始倒计时
    countdown.value = 60
    const timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
  } catch (error) {
    console.error('发送验证码失败:', error)
    if (error.response?.status === 409) {
      ElMessage.error('该手机号已注册，请直接登录')
    } else {
      ElMessage.error(error.response?.data?.message || '发送验证码失败')
    }
  } finally {
    sendingCode.value = false
  }
}

// 注册处理
const handleRegister = async () => {
  try {
    await formRef.value.validate()
    loading.value = true
    
    const registerData = {
      username: form.username,
      mobile: form.mobile,
      email: form.email,
      code: form.code,
      password: form.password
    }
    
    await userStore.register(registerData)
    
    ElMessage.success('注册成功！欢迎加入我们')
    
    // 注册成功后的处理
    setTimeout(() => {
      // 检查是否有重定向参数
      const redirect = route.query.redirect || '/home'
      
      // 确保重定向路径是安全的
      if (redirect.startsWith('/') && !redirect.startsWith('//')) {
        router.push(redirect)
      } else {
        router.push('/home')
      }
      
      // 清除URL中的redirect参数
      if (route.query.redirect) {
        router.replace({ 
          path: '/home', 
          query: {} 
        })
      }
    }, 1500)
    
  } catch (error) {
    console.error('注册失败:', error)
    
    // 详细的错误处理
    let errorMessage = '注册失败，请重试'
    
    if (error.response?.data?.message) {
      errorMessage = error.response.data.message
    } else if (error.message) {
      errorMessage = error.message
    } else if (error.response?.status === 409) {
      errorMessage = '用户名或手机号已被注册'
    } else if (error.response?.status === 400) {
      errorMessage = '验证码错误或已过期'
    }
    
    ElMessage.error(errorMessage)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.register-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.register-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  max-width: 1200px;
  width: 100%;
  background: white;
  border-radius: 20px;
  overflow: hidden;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1);
  min-height: 700px;
}

/* 左侧品牌区域 */
.brand-section {
  background: linear-gradient(135deg, #409eff 0%, #536dfe 100%);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 60px 40px;
  position: relative;
  overflow: hidden;
}

.brand-section::before {
  content: '';
  position: absolute;
  top: -50%;
  right: -50%;
  width: 200%;
  height: 200%;
  background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 1000'%3E%3Cg fill-opacity='0.03'%3E%3Cpolygon fill='%23fff' points='50 0 60 40 100 50 60 60 50 100 40 60 0 50 40 40'/%3E%3C/g%3E%3C/svg%3E") repeat;
  animation: float 20s infinite linear;
}

@keyframes float {
  0% { transform: translateY(0); }
  100% { transform: translateY(-100px); }
}

.brand-content {
  text-align: center;
  position: relative;
  z-index: 2;
}

.brand-logo {
  margin-bottom: 30px;
}

.brand-title {
  font-size: 2.5rem;
  font-weight: bold;
  margin: 0 0 15px 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.brand-subtitle {
  font-size: 1.1rem;
  margin-bottom: 40px;
  opacity: 0.9;
}

.brand-features {
  display: grid;
  grid-template-columns: 1fr;
  gap: 20px;
}

.feature-item {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 0.9rem;
  opacity: 0.9;
}

/* 右侧表单区域 */
.form-section {
  padding: 60px 40px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  overflow-y: auto;
}

.form-card {
  width: 100%;
  max-width: 400px;
  margin: 0 auto;
}

.form-header {
  text-align: center;
  margin-bottom: 30px;
}

.form-header h2 {
  font-size: 2rem;
  color: #2c3e50;
  margin: 0 0 10px 0;
  font-weight: 600;
}

.form-header p {
  color: #7f8c8d;
  margin: 0;
}

.register-form .el-form-item {
  margin-bottom: 20px;
}

.register-form .el-form-item__label {
  font-weight: 500;
  color: #333;
}

.code-input {
  display: flex;
  gap: 10px;
}

.code-input .el-input {
  flex: 1;
}

.code-btn {
  white-space: nowrap;
  min-width: 110px;
  background: #409eff;
  border-color: #409eff;
  color: white;
}

.code-btn:hover {
  background: #337ecc;
  border-color: #337ecc;
}

.code-btn:disabled {
  background: #c0c4cc;
  border-color: #c0c4cc;
  color: white;
}

.password-strength {
  margin-top: 8px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.strength-bar {
  flex: 1;
  height: 4px;
  background: #f0f0f0;
  border-radius: 2px;
  overflow: hidden;
}

.strength-fill {
  height: 100%;
  transition: all 0.3s ease;
}

.strength-text {
  font-size: 12px;
  font-weight: 500;
}

.register-btn {
  width: 100%;
  height: 48px;
  font-size: 16px;
  font-weight: 500;
  border-radius: 8px;
  background: #409eff;
  border: none;
  transition: all 0.3s ease;
}

.register-btn:hover:not(:disabled) {
  background: #337ecc;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.register-btn:disabled {
  background: #c0c4cc;
  border-color: #c0c4cc;
  color: white;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.form-footer {
  text-align: center;
  margin-top: 20px;
}

.divider {
  text-align: center;
  margin-bottom: 24px;
  position: relative;
}

.divider::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  height: 1px;
  background: #e4e7ed;
}

.divider span {
  background: white;
  padding: 0 16px;
  color: #909399;
  font-size: 14px;
}

.login-prompt {
  font-size: 14px;
  color: #606266;
}

.login-link {
  color: #409eff;
  text-decoration: none;
  margin-left: 5px;
}

.login-link:hover {
  text-decoration: underline;
}

.login-link:hover {
  text-decoration: underline;
}

.agreement-content {
  max-height: 400px;
  overflow-y: auto;
  line-height: 1.6;
}

.agreement-content h3 {
  color: #333;
  margin-bottom: 16px;
}

.agreement-content ol {
  padding-left: 20px;
}

.agreement-content li {
  margin-bottom: 8px;
}

@media (max-width: 768px) {
  .register-container {
    grid-template-columns: 1fr;
    max-width: 400px;
  }

  .brand-section {
    display: none;
  }

  .form-section {
    padding: 40px 30px;
  }

  .form-header h2 {
    font-size: 1.5rem;
  }

  .brand-features {
    grid-template-columns: 1fr;
  }

  .code-input {
    flex-direction: column;
  }

  .code-btn {
    min-width: auto;
  }
}

@media (max-width: 480px) {
  .register-page {
    padding: 10px;
  }

  .form-section {
    padding: 30px 20px;
  }
}
</style> 